from flask import Flask, request, jsonify, render_template
import json
import re
import webbrowser

app = Flask(__name__, template_folder='templates',
            static_folder='static', static_url_path='/static')


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/all')
def all():
    FILE_TMP = open('C:\\Windows\\System32\\drivers\\etc\\hosts', 'r')
    LINES_ARR = []
    for LINE in FILE_TMP:
        LINE = LINE.replace("\n", "").strip(' ')
        if LINE and not LINE.startswith('#'):
            LINES_ARR.append(re.split('\s+', LINE))
        else:
            LINES_ARR.append(LINE)
    FILE_TMP.close()
    return jsonify(LINES_ARR)


@app.route('/save', methods=['POST'])
def save():
    data = json.loads(request.get_data(as_text=True))
    FILE_TMP = open('C:\\Windows\\System32\\drivers\\etc\\hosts', 'w')
    for item in data['content']:
        if isinstance(item, list):
            FILE_TMP.write(item[0]+'    '+item[1]+'\n')
        elif isinstance(item, str):
            FILE_TMP.write(item+'\n')
        else:
            print('type error,is not str or list')
    return 'content'


port = 8010
url = 'http://127.0.0.1:'+str(port)
webbrowser.open(url=url, new=0)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=int(port), debug=True)
